<?php
declare(strict_types=1);

namespace polypay\ecc\serializer\signature\der;
// +----------------------------------------------------------------------
// | Title: 
// +----------------------------------------------------------------------
// | Author: 劳谦君子 <laoqianjunzi@qq.com>
// +----------------------------------------------------------------------
// | Date: 2021年09月22日
// +----------------------------------------------------------------------
// | Description：
// +----------------------------------------------------------------------

use polypay\asn\asn1\ASNObject;
use polypay\asn\asn1\Identifier;
use polypay\asn\asn1\universal\Integer;
use polypay\ecc\crypto\signature\Signature;
use polypay\ecc\crypto\signature\SignatureInterface;
use polypay\ecc\exception\SignatureDecodeException;

class Parser
{
 
    public function parse(string $binary): SignatureInterface
    {
        $offsetIndex = 0;
        $asnObject = ASNObject::fromBinary($binary, $offsetIndex);

        if ($offsetIndex != strlen($binary)) {
            throw new SignatureDecodeException('Invalid data.');
        }

        // Set inherits from Sequence, so use getType!
        if ($asnObject->getType() !== Identifier::SEQUENCE) {
            throw new SignatureDecodeException('Invalid tag for sequence.');
        }

        if ($asnObject->getNumberofChildren() !== 2) {
            throw new SignatureDecodeException('Invalid data.');
        }

        if (!($asnObject[0] instanceof Integer && $asnObject[1] instanceof Integer)) {
            throw new SignatureDecodeException('Invalid data.');
        }

        return new Signature(
            gmp_init($asnObject[0]->getContent(), 10),
            gmp_init($asnObject[1]->getContent(), 10)
        );
    }
}
